#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''=========================
@Time : 2021/3/29 23:33
@Coder: xh
@IDE  : PyCharm
========================='''
import requests
import time
import re
import random
import unicodedata
import cv2
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from PIL import  Image, ImageDraw, ImageFont
from moviepy.editor import *

def get_news():
    '''
    从网页爬取新闻
    :return: 列表形式的新闻资讯
    '''
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument('user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')

    driver = Chrome(options=chrome_options)
    with open(r'F:/GUI/早报/热点资讯30s/stealth.min.js') as f:
        js = f.read()
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
      "source": js
    })
    driver.implicitly_wait(30)#设置隐式等待
    print('开始抓取...')
    url = 'https://author.baidu.com/home?from=bjh_article&app_id=1681307856424533'
    driver.get(url)
    driver.maximize_window()
    click_1 = driver.find_element_by_xpath('/html/body/div[2]/div/div[4]/div[1]/div[1]/div/div[1]/div[1]/div/div[4]').click()
    url_2 = driver.find_element_by_xpath('/html/body/div[2]/div/div[4]/div[1]/div[1]/div/div[2]/div/div[1]/div/div/div[1]/div').get_attribute('url')
    print(url_2)
    driver.get(url_2)
    news_list = []
    for i in range(2,14):
        news = driver.find_element_by_xpath(f'/html/body/div/div/div/div[2]/div[2]/div[1]/div[1]/div[{i}]').text
        news = unicodedata.normalize('NFKC',news)
        news_list.append(news)
    # all_contents = driver.find_element_by_xpath('/html/body/div[2]/div/div[4]/div[1]/div[1]/div/div[2]/div/div[1]/div/div/div[1]/div').get_attribute('origin_title')
    # daily_news = all_contents.partition('！')[2].partition('【')[0]
    # daily_news = unicodedata.normalize('NFKC',daily_news)
    # news_list = daily_news.split('\n')[2:28:2]
    print(news_list)
    driver.close()
    print('抓取完成！')
    return news_list

news_list = get_news()

print('正在初始化参数...')
header = '热点资讯速览'
title = news_list[0]
ymd = title.split(' ')[0]
weekday = title.split(' ')[1]
lunar = title.split(' ')[2]
day = ymd.split('月')[1][:2]
#利用正则把日期分离出来作为文件名,有中文是ffmpeg会出错
date = re.sub('[\D]','',ymd)
contents = news_list[1:]
random.shuffle(contents)

my_img = Image.new('RGB',(1280,1920),'#f3f9f1')
my_img.save('bg3.jpg')
bg_img_list = ['bg1.jpg','bg2.jpg','bg3.jpg']
# img = random.choice(bg_img_list)
img = './bg4.jpg'

new_img = './{}.jpg'.format(date)
# compress_img = './{}.jpg'.format(date)  # 压缩后的图片

# 设置字体样式
font_type = 'C:/Windows/Fonts/Deng.ttf'
font_medium_type = 'C:/Windows/Fonts/Deng.ttf'
header_font = ImageFont.truetype(font_medium_type, 64)
title_font = ImageFont.truetype(font_medium_type,40)
ymd_font = ImageFont.truetype('‪C:\Windows\Fonts\msyhbd.ttc',48)#粗体
weekday_font = ImageFont.truetype('‪C:\Windows\Fonts\msyhbd.ttc',48)#粗体
lunar_font = ImageFont.truetype(r'‪C:\Windows\Fonts\msyhl.ttc',40)#细体
day_font = ImageFont.truetype('‪C:\Windows\Fonts\VIVALDII.TTF',108)#斜体
font = ImageFont.truetype(font_type, 30)
color = "#3d3b4f"
color1 = "#1142aa"
color2 = '#161823'

# 打开图片
image = Image.open(img)
draw = ImageDraw.Draw(image)
width, height = image.size

# header头
header_x = 320
header_y = 60
# draw.text((header_x, header_y), u'%s' % header, color, header_font)

#绘制长方形
draw.rectangle((80,70,1210,250),fill=None,outline=('#00A481'),width=2)
draw.rectangle((70,60,1200,240),fill=None,outline=('#00A481'),width=4)
# 标题
title_x = header_x - 140
title_y = header_y + 120
draw.text((title_x-80, title_y-100), u'%s' % ymd, '#00A888', ymd_font)
draw.text((title_x-80, title_y-20), u'%s' % lunar, '#00A888', lunar_font)
draw.text((800, title_y-100), u'%s' % weekday,'#00A888', weekday_font)
draw.text((1000, title_y), u'%s' % day,'#00A888', day_font)
#尾部
draw.rectangle((240,1800,1040,1800),fill=None,outline=('#00A481'),width=2)
legend_x = 640-(draw.textsize('Visualized By Python',lunar_font)[0]/2)
draw.text((legend_x,1840),u'%s' % 'Visualized By Python','#00A888',lunar_font)
# 当前时间
# cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# cur_time_x = 75
# cur_time_y = title_y+30
# cur_time_font = ImageFont.truetype(font_type, 20)
# draw.text((cur_time_x, cur_time_y), u'%s' %
#           cur_time, color, cur_time_font)
print('正在渲染内容...')
#移除超出一行的内容
over_length_content_list = []
for n,content in enumerate(contents):
    info = content.partition('、')[2]
    if draw.textsize(info,font)[0] >=2000:
        contents.pop(n)
    elif draw.textsize(info,font)[0] >= 1180:
        over_length_content = contents.pop(n)
        over_length_content_list.append(over_length_content)
# 绘制消息列表
def draw_info(x, y, short_news_list,long_news_list,linehigh, title_text):
    draw.text((x, y), u'%s' % (title_text), color, font)
    for rank_num, info in enumerate(short_news_list):
        info = str(rank_num+1)+'. '+info.partition('、')[2]
        height = rank_num * linehigh
        draw.text((x, y + height + 40), u'%s' % (info), color2, font,1)
    # for num,info in enumerate(long_news_list):
    #     rank_num = len(short_news_list)+num + 1
    #     info = str(rank_num) + '.' + info.partition('、')[2]
    #     check_num = 0
    #     for i in range(len(info)):
    #         if draw.textsize(info[:i+1],font)[0] >= 1180:
    #             check_num = i
    #             break
    #         else:
    #             check_num = 32
    #         if rank_num <= 9:
    #             info1 = info[:check_num]
    #             info2 = ' '*2+info[check_num:]
    #         else:
    #             info1 = info[:check_num+1]
    #             info2 = ' '*3 + info[check_num+1:]
    #     height = (rank_num - 1) * linehigh
    #     draw.text((x, y + height + 40), u'%s' % (info1), color2, font)
    #     draw.text((x, y + height + 100), u'%s' % (info2), color2, font)
            

linewith = 20
linehigh = 120
p_fenge = 20

# 绘制消息
news_x = 80
news_y = title_y + 80
title_text = ''
news_list = contents
draw_info(news_x, news_y, news_list,over_length_content_list,linehigh, title_text)

image.save(new_img, 'jpeg')

#将图片转为视频
def img2video():
    print('正在生成视频...')
    img = new_img
    fps = 30  # 保存视频的FPS，可以适当调整
    size = (1280, 1920)
    # 可以用(*'DVIX')或(*'X264'),如果都不行先装ffmepg: sudo apt-get install ffmepg
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    videoWriter = cv2.VideoWriter('./{}.avi'.format(date), fourcc, fps, size)  # 最后一个是保存图片的尺寸

    for i in range(1, 301):
        frame = cv2.imread(new_img)
        videoWriter.write(frame)
    videoWriter.release()

img2video()

def make_audio():
    video = VideoFileClip('./{}.avi'.format(date))
    sub_video1 = video.subclip(0,2).fadein(2,(1,1,1))
    sub_video2 = video.subclip(2,10)
    video = concatenate_videoclips([sub_video1,sub_video2])
    print(video.duration)
    audio = AudioFileClip(r'F:/GUI/早报/热点资讯30s/bgm1.mp3').subclip(0,10.0)
    print(audio.duration)
    video = video.set_audio(audio)
    video.write_videofile('./{}.mp4'.format(date))
    print('视频已生成，请查看！')

make_audio()